package hu.tozo.facade;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import hu.tozo.model.AmazonModel;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * http://en.wikipedia.org/wiki/Facade_pattern
 *
 * @author tozo
 */
public class AwsFacade {

    static AmazonEC2 ec2;          //WebService kliens
    private ArrayList<Instance> instances; //Amazon instance peldanyok
    static String separator = System.getProperty("file.separator");
    static String homeDir = System.getProperty("user.home");

    public AwsFacade() throws Exception {
        init();
    }
    public ArrayList<String> listInstances() {
        //Ebbe adjuk vissza a talalt instanceokat.
        ArrayList<String> ec2instances = new ArrayList<String>();
        try {
            DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
            System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones.");
            DescribeInstancesRequest dir = new DescribeInstancesRequest();
            DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
            List<Reservation> reservations = describeInstancesRequest.getReservations();
            setInstances(new ArrayList<Instance>());
            for (Reservation reservation : reservations) {
                getInstances().addAll(reservation.getInstances());
            }
            System.out.println("You have " + getInstances().size() + " Amazon EC2 instance(s).");
            Instance i = getInstances().get(0);
            for (Iterator<Instance> it = getInstances().iterator(); it.hasNext();) {
                Instance instance = it.next();
                //Itt adjuk hozza a peldanyt
                ec2instances.add(instance.getInstanceId());
            }

        } catch (AmazonServiceException ase) {
            System.out.println("Caught Exception: " + ase.getMessage());
            System.out.println("Reponse Status Code: " + ase.getStatusCode());
            System.out.println("Error Code: " + ase.getErrorCode());
            System.out.println("Request ID: " + ase.getRequestId());
        }
        return ec2instances;
    }

    /*
     * 1. Ellenorizni a futasi allapotot.
     * 2. Ha stop-ed allapotban van, csak akkor szabad elinditani.
     * TODO: Akkor ne inditsunk ra ha mar fut! AmazonInstance modell osztalyba
     * erdemes lenne bekotni ami kell.
     */
    public void startInstance(String id) {
        //sample: i-d1dea0e2
        StartInstancesRequest startRequest = new StartInstancesRequest().withInstanceIds(id);
        ec2.startInstances(startRequest);
    }

    public void stopInstance(String id) {
        StopInstancesRequest stopRequest = new StopInstancesRequest().withInstanceIds(id);
        ec2.stopInstances(stopRequest);
    }
    public String getPrivateIp(String id){
        String ip="";
        listInstances();
        for (Iterator<Instance> it = getInstances().iterator(); it.hasNext();) {
            Instance instance = it.next();
            if(instance.getInstanceId().equals(id)){
                ip = instance.getPrivateIpAddress();
            }
        }        
        return ip;
    }
    public int getInstanceState(String instanceId){
        int state = -1;
        listInstances();
        for (Iterator<Instance> it = getInstances().iterator(); it.hasNext();) {
            Instance instance = it.next();
            if(instance.getInstanceId().equals(instanceId)){
               state = instance.getState().getCode();
            }
        }        
        return state;
    }

    /*
     * WebService alapu kommunikacio, de rejtve van a fejleszto elol.
     * 
     */
    private static void init() throws Exception {
        File f = new File(homeDir + separator + "aws" + separator + "AwsCredentials.properties");
        AWSCredentials credentials = new PropertiesCredentials(f);
        ec2 = new AmazonEC2Client(credentials);
        ec2.setEndpoint("ec2.us-west-2.amazonaws.com");

    }

    /**
     * @return the instances
     */
    public ArrayList<Instance> getInstances() {
        return instances;
    }

    /**
     * @param instances the instances to set
     */
    public void setInstances(ArrayList<Instance> instances) {
        this.instances = instances;
    }

}
